package com.qingyun.web.controller.pcapi.resource;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpStatus;
import com.qingyun.common.annotation.Log;
import com.qingyun.common.annotation.RepeatSubmit;
import com.qingyun.common.config.QingYunConfig;
import com.qingyun.common.constant.Constants;
import com.qingyun.common.core.domain.AjaxResult;
import com.qingyun.common.core.page.TableDataInfo;
import com.qingyun.common.core.validate.AddGroup;
import com.qingyun.common.core.validate.EditGroup;
import com.qingyun.common.enums.BusinessType;
import com.qingyun.common.utils.poi.ExcelUtil;
import com.qingyun.security.controller.BaseController;
import com.qingyun.security.utils.SecurityUtils;
import com.qingyun.shop.domain.TiktokResource;
import com.qingyun.shop.domain.bo.resource.TiktokResourceAddBo;
import com.qingyun.shop.domain.bo.resource.TiktokResourceEditBo;
import com.qingyun.shop.domain.bo.resource.TiktokResourceGroupQueryBo;
import com.qingyun.shop.domain.bo.resource.TiktokResourceQueryBo;
import com.qingyun.shop.domain.vo.TiktokResourceGroupVo;
import com.qingyun.shop.domain.vo.TiktokResourceVo;
import com.qingyun.shop.service.ITiktokResourceGroupService;
import com.qingyun.shop.service.ITiktokResourceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * 资源Controller
 *
 * @author qingyun
 * @date 2021-09-04
 */
@Validated
@Api(value = "资源控制器", tags = {"^商户资源管理"})
@AllArgsConstructor
@RestController
@RequestMapping("/resource")
public class TiktokResourceController extends BaseController {

    private final ITiktokResourceService iTiktokResourceService;

	private final ITiktokResourceGroupService iTiktokResourceGroupService;
    /**
     * 查询资源列表
     */
    @ApiOperation("查询资源列表 resource:resource:list")
    @PreAuthorize("@ss.hasPermi('resource:resource:list')")
    @GetMapping("/list")
    public TableDataInfo<TiktokResourceVo> list(@Validated TiktokResourceQueryBo bo) {
        return iTiktokResourceService.queryPageList(bo);
    }

	@ApiOperation("删除本地资源文件")
	@PostMapping("/deleteFile")
	public AjaxResult deleteFile(@RequestParam("url") String url) {
    	if(StringUtils.isNotBlank(url)){
			String audioUrl = QingYunConfig.getProfile() + StringUtils.substringAfter( url, Constants.RESOURCE_PREFIX);
			File file = new File(audioUrl);
			boolean del = FileUtil.del(file);
			return AjaxResult.success(del);
		}
	return AjaxResult.error("地址不能为空");
	}

    /**
     * 获取资源详细信息
     */
    @ApiOperation("获取资源详细信息 resource:resource:query")
    @PreAuthorize("@ss.hasPermi('resource:resource:query')")
    @GetMapping("/{id}")
    public AjaxResult<TiktokResourceVo> getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(iTiktokResourceService.queryById(id));
    }

    @ApiOperation("修改资源状态 0待审核 1已通过 2未通过 2情况下需要携带context驳回原因")
	@PreAuthorize("@ss.hasPermi('resource:resource:editStatus')")
    @PostMapping("/editStatus")
    public AjaxResult editStatus(Long resourceId,Integer status,String context){
		TiktokResource resource = iTiktokResourceService.getById(resourceId);
		if (!resource.getStatus().equals(0)) {
			return AjaxResult.error("状态错误");
		}
		TiktokResource tiktokResource = new TiktokResource();
		tiktokResource.setId(resourceId);
		tiktokResource.setStatus(status);
		if(status.equals(2)){
			tiktokResource.setRemark(context);
		}
		iTiktokResourceService.updateById(tiktokResource);
		return AjaxResult.success("审核完成");
	}

    /**
     * 新增资源
     */
    @ApiOperation("新增资源 resource:resource:add")
    @PreAuthorize("@ss.hasPermi('resource:resource:add')")
    @Log(title = "新增资源", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/add")
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody TiktokResourceAddBo bo) {
		if (iTiktokResourceService.groupIdCheck(bo.getGroupId())) {
			return AjaxResult.error(HttpStatus.HTTP_BAD_REQUEST, "资源分组不存在，添加失败");
		}
        return toAjax(iTiktokResourceService.insertByBo(bo) ? 1 : 0);
    }

    /**
     * 修改资源
     */
    @ApiOperation("修改资源 resource:resource:edit")
    @PreAuthorize("@ss.hasPermi('resource:resource:edit')")
    @Log(title = "修改资源", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/edit")
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody TiktokResourceEditBo bo) {
        return toAjax(iTiktokResourceService.updateByBo(bo) ? 1 : 0);
    }

    /**
     * 删除资源
     */
    @ApiOperation("删除资源 resource:resource:remove")
    @PreAuthorize("@ss.hasPermi('resource:resource:remove')")
    @Log(title = "删除资源" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@PathVariable Long[] ids) {
        if (ids.length < 1) {
            return AjaxResult.error("删除资源id不能为空");
        }
        return toAjax(iTiktokResourceService.deleteWithValidByIds(Arrays.asList(ids), true) ? 1 : 0);
    }

	@ApiOperation("分组下拉列表")
	@GetMapping("/selectResourceList")
	public AjaxResult<Object> selectResourceList() {
		TiktokResourceGroupQueryBo tiktokResourceGroupQueryBo = new TiktokResourceGroupQueryBo();
		if (!SecurityUtils.isManager()) {
			tiktokResourceGroupQueryBo.setShopId(SecurityUtils.getShop().getId());
		}
		List<TiktokResourceGroupVo> tiktokResourceGroupVos = iTiktokResourceGroupService.queryList(tiktokResourceGroupQueryBo);

		return AjaxResult.success(tiktokResourceGroupVos);
	}
}
